/* 
 * File:   lua05.cpp
 * Author: Vicky.H
 * Email:  eclipser@163.com
 */
#include <iostream>
#include <lua.hpp> // -llua-5.1
#include <typeinfo>

/*
 * 
 */
int main(void) {


    lua_State* L = lua_open();
    luaL_openlibs(L);
    luaL_dofile(L, "lua05.lua");
    lua_getglobal(L, "sayHello");
    if (lua_isfunction(L, lua_gettop(L))) {
        auto f = lua_tocfunction(L, lua_gettop(L));
        std::cout << typeid (f).name() << std::endl; // PF i P9lua_StateE          (lua_State*)-> int

        lua_call(L, 0, 0);      // 简单的调用lua函数
    }
    
    std::cout << "\n---------------------------" << std::endl;
    
    lua_getglobal(L, "sayHello2");
    if (lua_isfunction(L, lua_gettop(L))) {
        auto f = lua_tocfunction(L, lua_gettop(L));
        std::cout << typeid (f).name() << std::endl; // PF i P9lua_StateE          (lua_State*)-> int
        
        lua_pushstring(L, "Vicky");
        lua_call(L, 1, 0);
    }
 
    std::cout << "\n---------------------------" << std::endl;
    
    lua_getglobal(L, "sayHello3");
    if (lua_isfunction(L, lua_gettop(L))) {
        auto f = lua_tocfunction(L, lua_gettop(L));
        std::cout << typeid (f).name() << std::endl; // PF i P9lua_StateE          (lua_State*)-> int
        
        lua_pushstring(L, "Vicky");
        lua_pushstring(L, "Jack");
        lua_call(L, 2, 0);
    }
    
    std::cout << "\n---------------------------" << std::endl;
    
    lua_getglobal(L, "sum");
    if (lua_isfunction(L, lua_gettop(L))) {
        auto f = lua_tocfunction(L, lua_gettop(L));
        std::cout << typeid (f).name() << std::endl; // PF i P9lua_StateE          (lua_State*)-> int
        
        lua_pushinteger(L, 1);
        lua_pushinteger(L, 7);
        lua_call(L, 2, 3);
        auto j = lua_tointeger(L, -1);
        auto i = lua_tointeger(L, -2);
        auto sum = lua_tointeger(L, -3);
        std::cout << "i = " << i << " j = " << j << " sum = " << sum << std::endl;
    }
    
    lua_close(L);
    return 0;
}
